import {
  Column,
  Entity,
  Index,
  JoinColumn,
  ManyToOne,
  OneToMany,
  PrimaryGeneratedColumn,
} from "typeorm";
import { Systems } from "./Systems";
import { RolePermissions } from "./RolePermissions";

@Index("parent_id", ["parentId"], {})
@Index("system_id", ["systemId"], {})
@Entity("permissions", { schema: "nest-demo" })
export class Permissions {
  @PrimaryGeneratedColumn({ type: "int", name: "id" })
  id: number;

  @Column("int", { name: "system_id", comment: "所属系统ID", unsigned: true })
  systemId: number;

  @Column("int", { name: "parent_id", nullable: true, comment: "父权限ID" })
  parentId: number | null;

  @Column("varchar", { name: "name", comment: "权限名称", length: 100 })
  name: string;

  @Column("varchar", {
    name: "code",
    comment: "权限代码(唯一标识)",
    length: 100,
  })
  code: string;

  @Column("enum", {
    name: "type",
    comment: "权限类型",
    enum: ["menu", "button", "api"],
  })
  type: "menu" | "button" | "api";

  @Column("varchar", {
    name: "path",
    nullable: true,
    comment: "菜单路径或API路径",
    length: 255,
  })
  path: string | null;

  @Column("varchar", {
    name: "icon",
    nullable: true,
    comment: "菜单图标",
    length: 100,
  })
  icon: string | null;

  @Column("int", {
    name: "sort",
    nullable: true,
    comment: "排序",
    default: () => "'0'",
  })
  sort: number | null;

  @Column("text", { name: "description", nullable: true, comment: "权限描述" })
  description: string | null;

  @Column("tinyint", {
    name: "status",
    nullable: true,
    comment: "状态: 0-禁用, 1-启用",
    default: () => "'1'",
  })
  status: number | null;

  @Column("timestamp", {
    name: "created_at",
    nullable: true,
    default: () => "CURRENT_TIMESTAMP",
  })
  createdAt: Date | null;

  @Column("timestamp", {
    name: "updated_at",
    nullable: true,
    default: () => "CURRENT_TIMESTAMP",
  })
  updatedAt: Date | null;

  @ManyToOne(() => Systems, (systems) => systems.permissions, {
    onDelete: "NO ACTION",
    onUpdate: "NO ACTION",
  })
  @JoinColumn([{ name: "system_id", referencedColumnName: "id" }])
  system: Systems;

  @ManyToOne(() => Permissions, (permissions) => permissions.permissions, {
    onDelete: "NO ACTION",
    onUpdate: "NO ACTION",
  })
  @JoinColumn([{ name: "parent_id", referencedColumnName: "id" }])
  parent: Permissions;

  @OneToMany(() => Permissions, (permissions) => permissions.parent)
  permissions: Permissions[];

  @OneToMany(
    () => RolePermissions,
    (rolePermissions) => rolePermissions.permission
  )
  rolePermissions: RolePermissions[];
}
